﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RiskMan.Config;
using XlDde;
using RiskMan.Models;
using System.Windows.Forms;
using RiskMan.Views.Dialogs;
using System.Reflection;

namespace RiskMan.Providers.Channels
{
    class DDEChannelOrderList : XlDdeChannel
    {
        private List<OrderModel> list;

        public DDEChannelOrderList()
        {
       
        }

        protected override void ProcessTable(XlTable xt, string topic)
        {
            list = RiskMan.MainWindow.StaticLevel._dataProvider.OrderList;
            try
            {
                for (int i = 0; i < xt.Rows; i++)
                {
                    OrderModel tmp = new OrderModel();
                    String time = "";
                    List<String> names = new List<String>();

                    for (int j = 0; j < xt.Columns; j++)
                    {
                        xt.ReadValue();
                        if (Namespace.Count == 0 && i == 0)
                        {
                            tmp = null;
                            names.Add(xt.StringValue);
                        }
                        else
                        {
                            if ( IsSend( xt ) == true )
                            {
                                try
                                {
                                    if ( Namespace [ j ] == "ACCOUNT" ) tmp.Account = xt.StringValue;
                                    if ( Namespace [ j ] == "SECCODE" ) tmp.Seccode = xt.StringValue;
                                    if ( Namespace [ j ] == "ORDERNUM" ) tmp.Number = ( long ) xt.FloatValue;
                                    if ( Namespace [ j ] == "BUYSELL" )
                                        if ( xt.StringValue == "B" )
                                            tmp.Operation = Cfg.Buy;
                                        else
                                            tmp.Operation = Cfg.Sell;
                                    if ( Namespace [ j ] == "BALANCE" ) tmp.OstCount = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "PRICE" ) tmp.Price = xt.FloatValue;
                                    if ( Namespace [ j ] == "QTY" ) tmp.Count = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "STATUS" )
                                    {
                                        if ( xt.StringValue == "FILLED" ) tmp.Status = Cfg.Performed;
                                        if ( xt.StringValue == "KILLED" ) tmp.Status = Cfg.Cancel;
                                        if ( xt.StringValue == "ACTIVE" ) tmp.Status = Cfg.Active;
                                    }
                                    if ( Namespace [ j ] == "ORDERDATE" ) time = xt.StringValue;
                                    if ( Namespace [ j ] == "ORDERTIME" )
                                        tmp.Time = DateTime.Parse( time + " " + xt.StringValue );
                                    if ( Namespace [ j ] == "CLIENTCODE" ) tmp.ClientCode = xt.StringValue;
                                    if ( Namespace [ j ] == "TRANSID" ) tmp.TID = ( int ) xt.FloatValue;
                                }
                                catch ( ArgumentOutOfRangeException )
                                {
                                    string message = "\"Таблица заявок\" в разных терминалах настроены по разному. \n\r" +
                                        "Для правильной настройки таблице ознакомьтесь с инструкцией." +
                                        "\n\rНеобходимо чтоб название и количество выводимых параметров совпадало.";
                                    if ( base.IsShowMessage == false )
                                    {
                                        base.IsShowMessage = true;
                                        new DialogMessage( message, "Ошибка" );
                                    }
                                    Cfg.SetLog( message, RiskMan.MainWindow.StaticLevel.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod() );
                                }
                                catch ( Exception ex )
                                {
                                    new DialogMessage( ex.Message, "DDEChannelOrderList" );
                                }
                            }
                            else
                            {
                                tmp = null;
                            }
                        }
                    }
                    if (tmp != null)
                    {
                        bool tr = false;
                        for (int r = 0; r < list.Count; r++)
                            if (list[r].Number == tmp.Number)
                            {
                                tr = true;
                                list[r] = tmp;
                                continue;
                            }

                        if (tr == false)
                            list.Add(tmp);
                    }
                    if (names.Count > 0)
                        Namespace = new List<String>(names);
                }
            }
            catch (Exception ex)
            {
                new DialogOkCancel( ex.Message, "DDEChannelOrderList" );
            }
        }

        public override void Disconnected(bool isConnected)
        {
            Namespace.Clear();
            QuikIntegration.dde.QuikUtil.StartDDE();
        }
    }
}
